<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h2 class="header-title">账号设置</h2>
          <p class="header-subtitle">管理您的账号信息和安全设置</p>
        </div>
      </template>
      
      <el-tabs v-model="activeTab">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-form :model="basicForm" :rules="basicRules" ref="basicFormRef" label-width="100px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="basicForm.username" disabled />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname">
              <el-input v-model="basicForm.nickname" placeholder="请输入昵称" />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="basicForm.phone" placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="basicForm.email" placeholder="请输入邮箱" />
            </el-form-item>
            <el-form-item label="性别">
              <el-radio-group v-model="basicForm.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
                <el-radio :label="2">保密</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="头像">
              <div class="avatar-uploader">
                <div class="avatar-wrapper">
                  <img v-if="basicForm.avatar" :src="basicForm.avatar" class="avatar-image" />
                  <i v-else class="el-icon-plus avatar-icon"></i>
                </div>
                <el-button type="primary" size="small" @click="handleAvatarUpload">上传头像</el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitBasicForm">保存修改</el-button>
              <el-button @click="resetBasicForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 修改密码 -->
        <el-tab-pane label="修改密码" name="password">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" placeholder="请输入当前密码" show-password />
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitPasswordForm">修改密码</el-button>
              <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <!-- 安全设置 -->
        <el-tab-pane label="安全设置" name="security">
          <div class="security-list">
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">登录验证</div>
                <div class="security-desc">开启后，登录时将会进行双重验证</div>
              </div>
              <div class="security-action">
                <el-switch v-model="securitySettings.loginVerify" @change="updateSecuritySetting('loginVerify')" />
              </div>
            </div>
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">登录通知</div>
                <div class="security-desc">开启后，异地登录将会发送通知</div>
              </div>
              <div class="security-action">
                <el-switch v-model="securitySettings.loginNotify" @change="updateSecuritySetting('loginNotify')" />
              </div>
            </div>
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">操作日志</div>
                <div class="security-desc">开启后，将记录您的关键操作</div>
              </div>
              <div class="security-action">
                <el-switch v-model="securitySettings.operationLog" @change="updateSecuritySetting('operationLog')" />
              </div>
            </div>
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">绑定手机</div>
                <div class="security-desc">已绑定手机：{{ basicForm.phone ? maskPhone(basicForm.phone) : '未绑定' }}</div>
              </div>
              <div class="security-action">
                <el-button type="primary" size="small" @click="handleBindPhone">{{ basicForm.phone ? '修改' : '绑定' }}</el-button>
              </div>
            </div>
            <div class="security-item">
              <div class="security-info">
                <div class="security-title">绑定邮箱</div>
                <div class="security-desc">已绑定邮箱：{{ basicForm.email ? maskEmail(basicForm.email) : '未绑定' }}</div>
              </div>
              <div class="security-action">
                <el-button type="primary" size="small" @click="handleBindEmail">{{ basicForm.email ? '修改' : '绑定' }}</el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 通知设置 -->
        <el-tab-pane label="通知设置" name="notification">
          <div class="notification-list">
            <div class="notification-item">
              <div class="notification-info">
                <div class="notification-title">系统通知</div>
                <div class="notification-desc">接收系统更新、维护等通知</div>
              </div>
              <div class="notification-action">
                <el-switch v-model="notificationSettings.system" @change="updateNotificationSetting('system')" />
              </div>
            </div>
            <div class="notification-item">
              <div class="notification-info">
                <div class="notification-title">活动通知</div>
                <div class="notification-desc">接收新活动、优惠等通知</div>
              </div>
              <div class="notification-action">
                <el-switch v-model="notificationSettings.activity" @change="updateNotificationSetting('activity')" />
              </div>
            </div>
            <div class="notification-item">
              <div class="notification-info">
                <div class="notification-title">消息提醒</div>
                <div class="notification-desc">接收新消息、回复等提醒</div>
              </div>
              <div class="notification-action">
                <el-switch v-model="notificationSettings.message" @change="updateNotificationSetting('message')" />
              </div>
            </div>
            <div class="notification-item">
              <div class="notification-info">
                <div class="notification-title">邮件通知</div>
                <div class="notification-desc">通过邮件接收重要通知</div>
              </div>
              <div class="notification-action">
                <el-switch v-model="notificationSettings.email" @change="updateNotificationSetting('email')" />
              </div>
            </div>
            <div class="notification-item">
              <div class="notification-info">
                <div class="notification-title">短信通知</div>
                <div class="notification-desc">通过短信接收重要通知</div>
              </div>
              <div class="notification-action">
                <el-switch v-model="notificationSettings.sms" @change="updateNotificationSetting('sms')" />
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    
    <!-- 绑定手机对话框 -->
    <el-dialog title="绑定手机" v-model="phoneDialogVisible" width="400px">
      <el-form :model="phoneForm" :rules="phoneRules" ref="phoneFormRef" label-width="80px">
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="phoneForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input v-model="phoneForm.code" placeholder="请输入验证码" />
            <el-button type="primary" :disabled="codeTimer > 0" @click="sendPhoneCode">
              {{ codeTimer > 0 ? `${codeTimer}秒后重发` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="phoneDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPhoneForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 绑定邮箱对话框 -->
    <el-dialog title="绑定邮箱" v-model="emailDialogVisible" width="400px">
      <el-form :model="emailForm" :rules="emailRules" ref="emailFormRef" label-width="80px">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="emailForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input v-model="emailForm.code" placeholder="请输入验证码" />
            <el-button type="primary" :disabled="emailCodeTimer > 0" @click="sendEmailCode">
              {{ emailCodeTimer > 0 ? `${emailCodeTimer}秒后重发` : '获取验证码' }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="emailDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEmailForm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 当前激活的标签页
const activeTab = ref('basic')

// 基本信息表单
const basicFormRef = ref(null)
const basicForm = reactive({
  username: 'admin',
  nickname: '管理员',
  phone: '13800138000',
  email: 'admin@example.com',
  gender: 1,
  avatar: 'https://ui-avatars.com/api/?name=Admin&background=3E78B2&color=fff'
})

// 基本信息表单校验规则
const basicRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 密码表单
const passwordFormRef = ref(null)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 安全设置
const securitySettings = reactive({
  loginVerify: true,
  loginNotify: true,
  operationLog: true
})

// 通知设置
const notificationSettings = reactive({
  system: true,
  activity: true,
  message: true,
  email: false,
  sms: false
})

// 手机绑定相关
const phoneDialogVisible = ref(false)
const phoneFormRef = ref(null)
const phoneForm = reactive({
  phone: '',
  code: ''
})
const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}
const codeTimer = ref(0)

// 邮箱绑定相关
const emailDialogVisible = ref(false)
const emailFormRef = ref(null)
const emailForm = reactive({
  email: '',
  code: ''
})
const emailRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  ]
}
const emailCodeTimer = ref(0)

// 初始化
onMounted(() => {
  // 可以在这里加载用户信息和设置
  loadUserInfo()
})

// 加载用户信息
const loadUserInfo = () => {
  // 模拟从API获取用户信息
  // 实际项目中应该调用API获取
  console.log('加载用户信息')
}

// 提交基本信息表单
const submitBasicForm = () => {
  basicFormRef.value.validate(valid => {
    if (valid) {
      // 模拟提交
      setTimeout(() => {
        ElMessage.success('基本信息修改成功')
      }, 500)
    }
  })
}

// 重置基本信息表单
const resetBasicForm = () => {
  basicFormRef.value.resetFields()
}

// 提交密码表单
const submitPasswordForm = () => {
  passwordFormRef.value.validate(valid => {
    if (valid) {
      // 模拟提交
      setTimeout(() => {
        ElMessage.success('密码修改成功')
        resetPasswordForm()
      }, 500)
    }
  })
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}

// 更新安全设置
const updateSecuritySetting = (key) => {
  // 模拟更新设置
  ElMessage.success(`${securitySettings[key] ? '开启' : '关闭'}${key === 'loginVerify' ? '登录验证' : key === 'loginNotify' ? '登录通知' : '操作日志'}成功`)
}

// 更新通知设置
const updateNotificationSetting = (key) => {
  // 模拟更新设置
  const settingNames = {
    system: '系统通知',
    activity: '活动通知',
    message: '消息提醒',
    email: '邮件通知',
    sms: '短信通知'
  }
  ElMessage.success(`${notificationSettings[key] ? '开启' : '关闭'}${settingNames[key]}成功`)
}

// 处理头像上传
const handleAvatarUpload = () => {
  // 模拟上传头像
  ElMessage.info('头像上传功能开发中...')
}

// 处理绑定手机
const handleBindPhone = () => {
  phoneForm.phone = basicForm.phone || ''
  phoneDialogVisible.value = true
}

// 发送手机验证码
const sendPhoneCode = () => {
  phoneFormRef.value.validateField('phone', (valid) => {
    if (!valid) {
      // 模拟发送验证码
      ElMessage.success('验证码已发送')
      codeTimer.value = 60
      const timer = setInterval(() => {
        codeTimer.value--
        if (codeTimer.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  })
}

// 提交手机绑定表单
const submitPhoneForm = () => {
  phoneFormRef.value.validate(valid => {
    if (valid) {
      // 模拟提交
      setTimeout(() => {
        basicForm.phone = phoneForm.phone
        ElMessage.success('手机绑定成功')
        phoneDialogVisible.value = false
      }, 500)
    }
  })
}

// 处理绑定邮箱
const handleBindEmail = () => {
  emailForm.email = basicForm.email || ''
  emailDialogVisible.value = true
}

// 发送邮箱验证码
const sendEmailCode = () => {
  emailFormRef.value.validateField('email', (valid) => {
    if (!valid) {
      // 模拟发送验证码
      ElMessage.success('验证码已发送')
      emailCodeTimer.value = 60
      const timer = setInterval(() => {
        emailCodeTimer.value--
        if (emailCodeTimer.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }
  })
}

// 提交邮箱绑定表单
const submitEmailForm = () => {
  emailFormRef.value.validateField(valid => {
    if (valid) {
      // 模拟提交
      setTimeout(() => {
        basicForm.email = emailForm.email
        ElMessage.success('邮箱绑定成功')
        emailDialogVisible.value = false
      }, 500)
    }
  })
}

// 手机号码脱敏
const maskPhone = (phone) => {
  return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : ''
}

// 邮箱脱敏
const maskEmail = (email) => {
  if (!email) return ''
  const parts = email.split('@')
  if (parts.length !== 2) return email
  const name = parts[0]
  const domain = parts[1]
  let maskedName = name
  if (name.length > 2) {
    maskedName = name.substring(0, 1) + '*'.repeat(name.length - 2) + name.substring(name.length - 1)
  }
  return `${maskedName}@${domain}`
}
</script>

<style scoped>
.settings-container {
  padding: 0;
}

.settings-card {
  margin-bottom: 20px;
}

.card-header {
  margin-bottom: 20px;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #1A2634;
}

.header-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 头像上传样式 */
.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar-wrapper {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 16px;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-icon {
  font-size: 28px;
  color: #8c939d;
}

/* 安全设置样式 */
.security-list {
  padding: 16px 0;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #1A2634;
}

.security-desc {
  font-size: 14px;
  color: #666;
}

/* 通知设置样式 */
.notification-list {
  padding: 16px 0;
}

.notification-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  color: #1A2634;
}

.notification-desc {
  font-size: 14px;
  color: #666;
}

/* 验证码输入框样式 */
.code-input {
  display: flex;
}

.code-input .el-input {
  margin-right: 10px;
}

.code-input .el-button {
  white-space: nowrap;
}
</style> 